package io.github.zhonglunsheng.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.StrUtil;
import io.github.zhonglunsheng.common.ZipUtil;
import io.github.zhonglunsheng.core.jdbc.JdbcTemplateHelper;
import io.github.zhonglunsheng.domain.SysTpl;
import io.github.zhonglunsheng.domain.bo.ImportTplBo;
import io.github.zhonglunsheng.service.SysTplService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * sys_tpl
 *
 * @author zhonglunsheng
 * 2022年7月5日 下午10:58:22
 */
@Service
public class SysTplServiceImpl implements SysTplService {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public List<SysTpl> queryByGroupName(String groupName) {
        return jdbcTemplate.queryForList("select * from sys_tpl where group_name = ?", groupName)
                .stream().map(item -> BeanUtil.toBean(item, SysTpl.class))
                .collect(Collectors.toList());
    }

    @Override
    public List<SysTpl> query(SysTpl sysTpl) {
        if (StrUtil.isNotBlank(sysTpl.getTplName())) {
            return jdbcTemplate.queryForList("select * from sys_tpl where tpl_name like ? or group_name like ?", sysTpl.getTplName(), sysTpl.getTplName())
                    .stream().map(item -> BeanUtil.toBean(item, SysTpl.class))
                    .collect(Collectors.toList());
        }

        if (StrUtil.isNotBlank(sysTpl.getGroupName())) {
            return jdbcTemplate.queryForList("select * from sys_tpl where  group_name = ?",  sysTpl.getGroupName())
                    .stream().map(item -> BeanUtil.toBean(item, SysTpl.class))
                    .collect(Collectors.toList());
        }

        return jdbcTemplate.queryForList("select * from sys_tpl")
                .stream().map(item -> BeanUtil.toBean(item, SysTpl.class))
                .collect(Collectors.toList());
    }

    @Override
    public boolean saveOrUpdate(SysTpl sysTpl) {
        JdbcTemplateHelper<SysTpl> helper = new JdbcTemplateHelper<>(jdbcTemplate, "sys_tpl");
        return helper.saveOrUpdate(sysTpl, LambdaUtil.getFieldName(SysTpl::getId)) > 0;
    }

    @Override
    public boolean removeById(String id) {
        JdbcTemplateHelper<SysTpl> helper = new JdbcTemplateHelper<>(jdbcTemplate, "sys_tpl");
        return helper.delete(SysTpl.builder().id(Long.parseLong(id)).build(), LambdaUtil.getFieldName(SysTpl::getId)) > 0;
    }

    @Override
    public List<SysTpl> groupByTplGroupName() {
        return jdbcTemplate.queryForList("select group_name from sys_tpl group by group_name")
                .stream().map(item -> BeanUtil.toBean(item, SysTpl.class))
                .collect(Collectors.toList());
    }

    @Override
    public boolean importTpl(String zipPath, String target, ImportTplBo importTplBo) {
        try {
            Files.deleteIfExists(Paths.get(target));
            // 解压压缩包
            ZipUtil.unzipFile(zipPath, target);
            // 遍历目录获取所有模板
            List<File> files = new ArrayList<>();
            getDirectory(new File(target), files);

            // 删除之前的模板
            jdbcTemplate.update("delete from sys_tpl where group_name = ? and tpl_type = ?", importTplBo.getProjectName(), importTplBo.getProjectName());

            // 读取所有文件路径 、 文件内容 、 文件名 保存到数据库
            for (File file : files) {
                String path = file.getPath();
                List<String> content = FileUtil.readLines(file, StandardCharsets.UTF_8);
                String fileName = file.getName() + "." + UUID.randomUUID().toString().substring(0, 4).toLowerCase() + ".enjoy";
                String groupName = importTplBo.getProjectName();

                saveOrUpdate(SysTpl.builder()
                        .groupName(groupName)
                        .content(CollUtil.isEmpty(content) ? "" : CollUtil.join(content, "\n"))
                        .createTime(new Date())
                        .updateTime(new Date())
                        .fileName(fileName)
                        .filePath(handleFilePathVar(target, importTplBo, path))
                        .status("0")
                        .tplType(groupName)
                        .build());

            }
            // 删除临时文件
            Files.deleteIfExists(Paths.get(target));
            Files.deleteIfExists(Paths.get(zipPath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    private String handleFilePathVar(String tplBasePath, ImportTplBo importTplBo, String codeGenPath) {
        codeGenPath =  codeGenPath.replace(tplBasePath, importTplBo.getBasePrefix());
        List<Map<String, String>> pathVar = importTplBo.getPathVar();
        for (Map<String, String> item : pathVar) {
            codeGenPath = codeGenPath.replaceAll(item.get("src"), item.get("dst"));
        }
        return codeGenPath;
    }

    private void getDirectory(File file, List<File> files) {
        File flist[] = file.listFiles();
        if (flist == null || flist.length == 0) {
            return;
        }
        for (File f : flist) {
            if (f.isDirectory()) {
                //这里将列出所有的文件夹
                getDirectory(f, files);
            } else {
                //这里将列出所有的文件
                files.add(f);
            }
        }
    }
}




